import { reqCartList, reqdeleteCartId, reqUpdateCheckedById } from '../../api/index'
const state = {
    cartlist: []
}
const mutations = {
    REQCARTLIST(state, cartlist) {
        state.cartlist = cartlist
    }
}
const actions = {
    // 获取购物车数据
    async getCartList({ commit }) {
        let res = await reqCartList()
        if (res.code == 200) {
            commit('REQCARTLIST', res.data)
        }
    },
    // 删除购物车id产品
    async deleteCartListBySkuId({ commit }, skuId) {
        let res = await reqdeleteCartId(skuId)
        if (res.code == 200) {
            return 'ok'
        } else {
            return new Error('faile')
        }
    },
    //修改id商品勾选状态 
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let res = await reqUpdateCheckedById(skuId, isChecked)
        if (res.code == 200) {
            return 'ok'
        } else {
            return new Error('faile')
        }
    },
    // 删除所有勾选的商品
    deleteAllCheckedCart(context) {
        // context 就是仓库
        // let carts = context.getters.cartList.cartInfoList
        // let result = carts.fllter(cart => cart.isChecked == 1)
        let PromiseAll = []
        context.getters.cartList.cartInfoList.forEach(item => {
                let promise = item.isChecked == 1 ? context.dispatch('deleteCartListBySkuId', item.skuId) : ''
                PromiseAll.push(promise)
            })
            // Promise.all返回一个的结果在于数组中的promise对象是全部成功返回成功 有一个失败就返回失败
        return Promise.all(PromiseAll)
    },
    // 修改全部商品状态
    updateAllCartChecked({ dispatch, state }, isChecked) {
        let promiseAll = []
        state.cartlist[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartlist[0] || {}
    },
    // 计算出来的购物车数据
    // cartInfoList(state) {
    //     return state.cartInfoList
    // }
}
export default {
    state,
    mutations,
    actions,
    getters
}